import React, {useEffect, useState} from 'react'
import {Button, Form, message} from 'antd'
import {history, connect} from 'umi'
import {Basics, CollectionAccount} from '../components'
import Styles from './index.less'
import {addDitch, getDitchDetail, updateChannel} from '@/service/channel'
import {getDriverPresent} from '@/service/customer/driver'
import {getFleetPresent} from '@/service/customer/fleet'
import {getProvinceDataByCityName} from '@/service/common'

const add = (props: any) => {
	// eslint-disable-next-line react/destructuring-assignment
	const routerQuery = props.location.query
	// eslint-disable-next-line prefer-destructuring
	const pageType = routerQuery.pageType
	const [loading, setLoading] = useState(false)
	const [detailRecord, setDetailRecord] = useState<any>({})
	const [basicsForm] = Form.useForm()
	const [collectionAccountForm] = Form.useForm()
	const [phoneStatus, setPhoneStatus] = useState<boolean>() // 判断联系电话是否存在

	useEffect(() => {
		if (pageType) {
			getDitchDetail({id: routerQuery.id}).then((res: any) => {
				if (res.data) {
					if (res?.data.cityName) {
						getProvinceDataByCityName({
							cityName: res?.data.cityName,
						}).then((result: any) => {
							if (result.data) {
								setDetailRecord({
									...res.data,
									cityId: [
										result?.data?.provinceId,
										res?.data?.cityId,
									],
								})
							}
						})
					}
				}
			})
		}
	}, [pageType])

	// const onSave = async () => {
	//   try {
	//     referrerForm.resetFields();
	//     const data = await referrerForm.validateFields();
	//     addDitch
	//     console.log(data, 'data');
	//   } catch (error) {
	//     // eslint-disable-next-line no-console
	//     console.log(error, 'error');
	//   }
	// };
	// eslint-disable-next-line consistent-return

	const onSubmit = async (formD: any) => {
		setLoading(true)
		if (pageType === 'edit') {
			const newData = {...formD, id: routerQuery.id}
			const res = await updateChannel(newData)
			if (res.success) {
				message.success('修改成功')
				history.push({
					pathname: '/merchantCenter/channel/list',
				})
			}
		} else {
			const res = await addDitch(formD)
			if (res.success) {
				message.success('保存成功')
				history.push({
					pathname: '/merchantCenter/channel/list',
				})
			}
		}
		setTimeout(() => setLoading(false), 1000)
	}
	// 自营-BD，判断车队长联系电话是否存在
	const fleetPhone = (basicsFormData: any, type?: string) => {
		getFleetPresent({
			phone: basicsFormData?.phone,
		}).then((res: any) => {
			if (res?.data) {
				if (type) {
					setPhoneStatus(false)
					message.warning('联系电话已存在车队列表')
					setLoading(false)
				} else {
					setPhoneStatus(true)
				}
			} else if (type) {
				setPhoneStatus(true)
			} else {
				setLoading(false)
				setPhoneStatus(false)
				message.warning('车队长联系电话不存在')
			}
		})
	}
	// 司推司，判断司机联系电话是否存在
	const driverPhone = (basicsFormData: any, type?: string) => {
		const queryData: any = {}
		if (window.apiPrefixUri) {
			queryData.tel = basicsFormData?.phone
		} else {
			queryData.phone = basicsFormData?.phone
		}
		if (basicsFormData?.driverId) {
			queryData.driverId = basicsFormData?.driverId
		}
		getDriverPresent(queryData).then((res: any) => {
			if (res?.data) {
				if (type) {
					message.warning('联系电话已存在司机列表')
					setPhoneStatus(false)
					setLoading(false)
				} else {
					setPhoneStatus(true)
				}
			} else if (type) {
				fleetPhone(basicsFormData, type)
			} else {
				setLoading(false)
				setPhoneStatus(false)
				message.warning('司机联系电话或司机ID不存在')
			}
		})
	}

	const onSaveData = async () => {
		const basicsFormData = await basicsForm.validateFields()
		const collectionAccountFormData =
			await collectionAccountForm.validateFields()
		if (basicsFormData && collectionAccountFormData) {
			const formD = {
				...basicsFormData,
				...collectionAccountFormData,
			}
			formD.channelType = `${formD?.firstLevelType},${formD?.secondLevelType}`
			if (formD?.cityId) {
				formD.cityId = formD?.cityId?.[1] || formD.cityId
			}
			delete formD?.firstLevelType
			delete formD?.secondLevelType
			onSubmit(formD)
		}
	}
	useEffect(() => {
		if (phoneStatus) {
			onSaveData()
		}
	}, [phoneStatus])

	const onSave = async () => {
		setPhoneStatus(false)
		const basicsFormData = await basicsForm.validateFields()
		const collectionAccountFormData =
			await collectionAccountForm.validateFields()
		if (basicsFormData && collectionAccountFormData) {
			if (basicsFormData?.secondLevelType === '3') {
				setPhoneStatus(true)
			} else if (basicsFormData?.secondLevelType === '4') {
				driverPhone(basicsFormData)
			} else if (basicsFormData?.secondLevelType === '5') {
				driverPhone(basicsFormData, '普推司')
			}
		} else {
			setTimeout(() => setLoading(false), 1000)
		}
	}
	return (
		<div className={Styles.add}>
			<Basics
				pageType={pageType}
				basicsForm={basicsForm}
				detailRecord={detailRecord}
				user={props?.user}
			/>
			<CollectionAccount
				pageType={pageType}
				collectionAccountForm={collectionAccountForm}
				detailRecord={detailRecord}
			/>
			{/* <ChannelCode
        channelCodeList={channelCodeList}
        setChannelCodeList={setChannelCodeList}
        pageType={pageType}
        detailRecord={detailRecord}
      /> */}
			<div className={Styles.operation}>
				{pageType !== 'detail' && (
					<Button
						type="primary"
						htmlType="submit"
						loading={loading}
						onClick={onSave}>
						保存
					</Button>
				)}

				<Button
					style={{marginLeft: '5px;'}}
					onClick={() => {
						history.go(-1)
					}}>
					取消
				</Button>
			</div>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(add)
